﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

using iTextSharp.text;
using iTextSharp.text.pdf;

namespace iPdf
{
    class PdfEncryptor : SinglePdfManipulator<EncryptOption>
    {
        protected bool IsPasswordSecurity
        {
            get
            {
                return pageOption.SecurityLevelId == SecurityLevelId.PasswordSecurity;
            }
        }

        protected override void ReadPdf(string fileName)
        {
            if (IsPasswordSecurity)
            {
                reader = new PdfReader(fileName, DocWriter.GetISOBytes(pageOption.OwnerPassword));
            }
            else
            {
                reader = new PdfReader(fileName,
                                pageOption.Certificate.GetCertificates()[0],
                                pageOption.Certificate.PrivateKey);
            }
        }

        protected override void Manipulate()
        {
            if (IsPasswordSecurity)
            {
                stamper.SetEncryption(PdfWriter.STRENGTH128BITS, pageOption.OpenPassword,
                    pageOption.OwnerPassword, pageOption.Permission.Permissions);
            }
            else
            {
                stamper.SetEncryption(pageOption.Certificate.GetCertificates(),
                                                new int[] { pageOption.Permission.Permissions }, PdfWriter.STANDARD_ENCRYPTION_128);
            }
        }

    }
}
